package com.myl.admin.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.myl.admin.domain.vo.LoginVO;
import com.myl.admin.service.ILoginService;
import com.myl.core.domain.entity.SysUser;
import com.myl.core.exception.ServiceExceptionHandler;
import com.myl.core.mapper.SysUserMapper;
import com.myl.core.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * LoginServiceImpl
 * author: myl <ixiaomu@qq.com> 2024/1/10
 * tips:
 */
@Slf4j
@Service
public class LoginServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ILoginService {
    @Override
    public Object doLogin(String username, String password) {
        // 根据用户名获取用户信息
        SysUser user = Db.lambdaQuery(SysUser.class).eq(SysUser::getUsername, username).one();
        if (user == null) {
            throw new ServiceExceptionHandler("账号或密码不正确" );
        }
        // 核对密码
        if (!password.equals(user.getPassword())) {
            throw new ServiceExceptionHandler("登录失败，账号或密码不正确" );
        }
        // 执行登录
        StpUtil.login(user.getId());

        // 更新登录信息
        user.setLastIp(IpUtils.getHostIp());
        user.setLastTime(DateUtil.date().toLocalDateTime());
        updateById(user);
        // 记录登录日志
        // TODO

        // 返回登录信息
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        LoginVO loginToken = new LoginVO();
        loginToken.setToken(tokenInfo.getTokenValue());
        loginToken.setTimeout(tokenInfo.getTokenTimeout());
        return loginToken;
    }

    @Override
    public void doLogout() {

    }
}
